package com.sinosoft.web.common.shiro.interceptors;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object handler, Exception ex) {
        // Expose ModelAndView for chosen error view.
        String viewName = determineViewName(ex, request);
        if (viewName != null) {
            // JSON格式返回
            String requestType = request.getHeader("X-Requested-With");// (获得extjs session过期值)
            if (requestType != null && requestType.contains("XMLHttpRequest") && request.getHeader("accept").contains("application/json")) {
                try {
                    PrintWriter writer = response.getWriter();
                    response.addHeader("UnauthorizedException", "true");
                    response.setContentType("text/html;charset=utf-8");
                    writer.write(ex.getMessage());
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return getModelAndView(viewName, ex, request);
            } else {
                // JSP格式返回
                // 如果不是异步请求
                // Apply HTTP status code for error views, if specified.
                // Only apply it if we're processing a top-level request.
                Integer statusCode = determineStatusCode(request, viewName);
                if (statusCode != null) {
                    applyStatusCodeIfPossible(request, response, statusCode);
                }
                return getModelAndView(viewName, ex, request);
            }
        } else {
            return null;
        }
    }
}
